// pages/order_appeal/index.js
import {
    getNavigationbar
} from "../../api/index.js"
const md5 = require('../../utils/md5code.js');
import {
    HEADER,
    CACHE_TOKEN,
    HTTP_REQUEST_URL,
    HTTP_REQUEST_FILE_URL
} from '../../config.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        appeal:'',
          // 凭证上传预览集合
          fileList: [],
          resDobj:{}
    },
    /**
     * 上传凭证触发回调函数完成后
     * @param {*} e 
     */
    handleUpdAfterRead(e) {
        console.log('图片上传', e)
        const {
            tempFilePath
        } = e.detail.file

        let file = e.detail
        console.log("e.detail", e.detail, HTTP_REQUEST_FILE_URL)
        this.parseUrl(file.file.url).then(res => {
            console.log('res', res)
            // this.setData({
            //     fileList: this.data.fileList.concat('http://static.chonglaoban.cn/' + res.imgsrc[0])
            // })
            this.data.fileList.push({
                url: 'http://static.chonglaoban.cn/' + res.imgsrc[0]
            })
            this.setData({
                fileList: this.data.fileList
            })
        });



        // this.setData({
        //     fileList: this.data.fileList
        // })
    },
    base64_decode(input) { // 解码，配合decodeURIComponent使用
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = base64EncodeChars.indexOf(input.charAt(i++));
            enc2 = base64EncodeChars.indexOf(input.charAt(i++));
            enc3 = base64EncodeChars.indexOf(input.charAt(i++));
            enc4 = base64EncodeChars.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        return (output);
    },
    signatureProcess(data) {
        let keys = Object.keys(data).sort()
        let query = keys.map(key => {
            return `${key}=${data[key]}`
        }).join('&')
        let signStr = md5.hexMD5(query).toUpperCase() + "code=APPStatic#@#&"
        let signFinal = md5.hexMD5(signStr).toUpperCase()
        return signFinal
    },
    parseUrl(url) {
        let that = this
        const commonParams = {
            sys_type: 'app',
            version_name: '6.16.0',
            client_device: 'wechat_xcx',
            timestamp: parseInt(Date.now() / 1000),
            token: wx.getStorageSync(CACHE_TOKEN)
        }
        commonParams['sign'] = that.signatureProcess(commonParams)
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: 'https://static.chonglaoban.cn/FileOperate/multiImageUpload',
                filePath: url,
                name: 'imgFile',
                header: {
                    "Content-Type": "multipart/form-data"
                },
                formData: commonParams,
                success: function (res) {
                    res.data = JSON.parse(res.data)
                    res.data.data = JSON.parse(that.base64_decode(res.data.data))
                    console.log(res)
                    resolve(res.data.data)
                },
                fail: function (err) {
                    console.error('请求失败', err);
                    reject(err)
                }
            })
            wx.hideLoading();
        })
    },
    /**
     * 移除上传凭证预览
     * @param {*} e 
     */
    handleUpdDel(e) {
        console.log('1', e);
        let indexImg = e.detail.index
        let num = this.data.fileList.filter((item, index) => index !== indexImg);
        console.log('num', num)
        this.setData({
            fileList: num
        })
    },
    /**
     * 提交表单回调函数方法
     * @param {*} e 
     */
    handleFormSubmit(e) {
        const {
            value
        } = e.detail
        console.log("表单对象", value, this.data.fileList);
        let fileName
        const newUrls = this.data.fileList.map(item => item.url);
        const urlsString = JSON.stringify(newUrls);
        console.log(newUrls);
        getNavigationbar({
            act: 'order_appeal',
            id: this.data.resDobj.id || '',
            appeal_reason: this.data.description || this.data.resDobj.description,
            appeal_vouch: urlsString,
        }).then(res => {
            console.log('修改申请', res)
            if (res.result == 101) {
                getApp().Tips({
                    title: res.msg
                })
            } else {
                wx.navigateBack({
                    delta: 1
                })
                wx.showToast({
                    title: '申诉成功',
                    duration: 2000
                });
            }
        })
    },
    Inuptappeal(e) {
        console.log('e',e.detail.value)
        this.data.description = e.detail.value
    },
    handleUpdDel(e) {
        console.log('e1', e.detail.index)
        let indexImg = e.detail.index
        let num = this.data.fileList.filter((item, index) => index !== indexImg);
        console.log('num', num)
        this.setData({
            fileList: num
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            const params = JSON.parse(options.data)
            console.log('进', params)
            const data = params
            this.data.resDobj = data
            console.log('this.data.actions', this.data.actions)
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})